package com.atguigu.n_producer_consumer_lock;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*一个生产者 一个消费者 每生产一个就要被吃掉一个 交替十次*/
class Cake{
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    // 蛋糕的数量
    int num = 0;


    // 生产者 如果有蛋糕则不生产 通知消费者
    public void producer() throws InterruptedException {
        lock.lock();
        try {
            while (num!=0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"生产一个蛋糕，此时蛋糕的数量是"+(++num));
            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }
    // 消费者 如果没有蛋糕则不消费 通知生产者
    public void consumer() throws InterruptedException {
        while (num==0){
            condition.await();
        }
            System.out.println(Thread.currentThread().getName()+"消费一个蛋糕，此时蛋糕的数量是"+(--num));
            condition.signalAll();
    }
}

public class Test {
    public static void main(String[] args) {
        Cake c1 = new Cake();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    c1.producer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"a").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    c1.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"b").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    c1.producer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"c").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    c1.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"d").start();
    }
}
